package com.zhiyan.security.account.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.zhiyan.common.util.model.Page;
import com.zhiyan.security.account.dao.AccountDao;
import com.zhiyan.security.account.domain.entity.Account;
import com.zhiyan.test.dao.TestDao;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
	@Autowired 
	private AccountDao accountDao;
	
	@Override
	public void add(Account account){
		try {
			String id = "account" + UUID.randomUUID().toString().replace("-", "");
			account.setId(id);
			account.setIsDelete("1");
			accountDao.add(account);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public void update(Account account) {
		try {
			accountDao.update(account);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		
	}

	@Override
	public List<Account> query(Map<String, Object> map) {
		try {
			List<Account> list = accountDao.query(map);
			return list;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public List<Account> queryPage(Page page, Map<String, Object> map) {
		try {
			List<Account> list = accountDao.query(map);
			int total = list.size();
			page.setTotal(total);
			
			int pageNo = page.getPageNo();
			int pageSize = page.getPageSize();
			int start = (pageNo-1)*pageSize;
			int pageTotal = total%pageSize==0?total/pageSize:total/pageSize+1;
			page.setPageTotal(pageTotal);
			
			map.put("start", start);
			map.put("size", pageSize);
			list = accountDao.query(map);
			return list;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public void delete(List<String> idList) {
		try {
			accountDao.delete(idList);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public Account findByLoginName(String loginName) {
		try {
			Account account = new Account();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("loginName", loginName);
			List<Account> accountList = accountDao.query(map);
			if (accountList!=null && accountList.size()>0) {
				account = accountList.get(0);
			}
			return account;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
